const fs = require("fs")
const os = require("os")
class RcParser {
  #path;

  #contentList = [];

  #config = {};

  constructor(filePath) {
    this.#path = filePath;
  }

  parse() {
    if (!fs.existsSync(this.#path)) {
    }
    const content = fs.readFileSync(this.#path, 'utf-8');
    const lines = content.split(os.EOL);
    lines.forEach((line) => {
      if (line.startsWith('#')) {
        this.#contentList.push(line);
      } else {
        const index = line.indexOf('=');
        if (index >= 0) {
          const key = line.substr(0, index).trim();
          const value = line.substr(index + 1).trim();
          this.#contentList.push(key);
          this.#config[key] = value;
        }
      }
    });
  }

  get(key) {
    return this.#config[key];
  }

  set(key, value) {
    this.#config[key] = value;
    if (!this.#contentList.includes(key)) {
      this.#contentList.push(key);
    }
  }

  delete(key) {
    delete this.#config[key];
    const index = this.#contentList.indexOf(key);
    if (index >= 0) {
      this.#contentList.splice(index, 1);
    }
  }

  setJson(json) {
    if (!json) {
    }
    Object.keys(json).forEach((key) => {
      this.set(key, json[key]);
    });
  }

  toJson() {
    return this.#config;
  }

  toString() {
    const content = this.#contentList.map((c) => {
      if (!c.startsWith('#')) {
        if (this.#config[c] !== undefined) {
          return `${c} = ${this.#config[c]}`;
        }
        return '';
      }
      return c;
    });
    return content.join(os.EOL);
  }

  save() {
    fs.writeFileSync(this.#path, this.toString());
  }
}

RcParser.fromJson = (json, filePath) => {
  const parser = new RcParser(filePath);
  parser.setJson(json);
  return parser;
};

RcParser.fromPath = (filePath) => {
  const parser = new RcParser(filePath);
  parser.parse();
  return parser;
};

RcParser.saveJsonToFile = (json, filePath) => {
  const parser = RcParser.fromJson(json, filePath);
  parser.save();
  return parser;
};


module.exports = RcParser